package com.itheima.dao.impl;

import com.itheima.common.ProductConst;
import com.itheima.dao.ProductDao;
import com.itheima.pojo.Product;
import com.itheima.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.util.List;

/**
 * @author ZhangYan
 * @Date 2021/1/16
 */
public class ProductDaoImpl implements ProductDao {
    //构建QueryRunner对象 用于还行sql语句
    private QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

    //查询热门商品
    @Override
    public List<Product> findHot() throws Exception {
        //sql语句
        String sql = "select * from product where is_hot = ? limit ?";
        Object[] params = {ProductConst.HOT,ProductConst.HOTTEST_SHOW};
        return queryRunner.query(sql,new BeanListHandler<>(Product.class),params);
    }

    //查询最新商品
    @Override
    public List<Product> findNew() throws Exception {
        //sql语句
        String sql = "select * from product order by pdate desc limit ?";
        Object[] params = {ProductConst.NEWEST_SHOW};
        return queryRunner.query(sql,new BeanListHandler<>(Product.class),params);
    }

    //根据ID查询商品详情
    @Override
    public Product finById(String pid) throws Exception {
        String sql = "select * from product where pid = ?";

        return queryRunner.query(sql,new BeanHandler<>(Product.class),pid);
    }

    //分页查询
    //查询某cid分类下所有商品个数
    @Override
    public long totalCount(String cid) throws Exception {
        String sql = "select count(*) from product where cid=?";
        Object[] params = {cid};

        /*
        query方法中RequestSetHandler  类型列表
        AbstractListHandler —————— 返回多行List的抽象类

        ArrayHandler    ——————   返回一行的Object[]

        ArrayListHandler ——————   返回List，每行是Object[]

        BeanHandler     ——————   返回第一个Bean对象

        BeanListHandler ——————   返回List，每行是Bean

        ColumnListHandler —————— 返回一列的List

        KeyedHandler  ——————返回Map，具体见代码

        MapHandler     ——————   返回单个Map

        MapListHandler   ——————  返回List，每行是Map

        ScalarHandler     ——————   返回列的头一个值
        */
        return queryRunner.query(sql,new ScalarHandler<>(),params);
    }

    /**
     *
     * @param cid  分类ID
     * @param currentPage 当前页码
     * @param pageSize 每页显示个数
     * @return
     * @throws Exception
     */
    //查询该cid分类下所有商品信息
    @Override
    public List<Product> findByPage(String cid, int currentPage, int pageSize) throws Exception {
        String sql = "select * from product where cid=? limit ?,?";
        //
        Object[] params = {cid,(currentPage-1)*pageSize,pageSize};
        return queryRunner.query(sql,new BeanListHandler<>(Product.class),params);
    }
}
